package com.car.rental.vehicle.listener;

import com.car.rental.vehicle.service.VehicleService;
import com.car.rental.vehicle.enums.VehicleStatus;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class PaymentMessageListener {

    private final VehicleService vehicleService;

    @RabbitListener(queues = "payment.status.queue")
    public void handlePaymentSuccess(Map<String, Object> message, Channel channel, Message originalMessage) {
        try {
            String paymentNo = (String) message.get("paymentNo");
            Long vehicleId = (Long) message.get("vehicleId");
            Integer status = (Integer) message.get("status");
            
            log.info("收到支付状态变更消息，支付流水号：{}，车辆ID：{}，状态：{}", paymentNo, vehicleId, status);
            
            // 只有在支付成功时才更新车辆状态
            if (status != null && status == 1) {  // 1 表示支付成功
                // 更新车辆状态为已租出
                vehicleService.updateStatus(vehicleId, VehicleStatus.RENTED.getCode());
                log.info("更新车辆状态为已租出，车辆ID：{}", vehicleId);
            }
            
            channel.basicAck(originalMessage.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("处理支付消息失败", e);
            try {
                channel.basicNack(originalMessage.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ex) {
                log.error("消息确认失败", ex);
            }
        }
    }
} 